package top.jacktgq.web.servlet;
/**
 * @Author CandyWall
 * @Date 2021/6/20--12:33
 * @Description 处理学生信息的servlet
 */

import top.jacktgq.dao.StudentDao;
import top.jacktgq.pojo.PageBean;
import top.jacktgq.pojo.Student;
import top.jacktgq.utils.MapperUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "GetStudentServlet", value = "/getStudents")
public class GetStudentsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String currentPageStr = request.getParameter("currentPage");
        //如果首次访问，当前页为空，置为1
        int currentPage = 1;
        int currentCount = 5;
        if (currentPageStr != null) {
            currentPage = Integer.parseInt(currentPageStr);
            currentCount = Integer.parseInt(request.getParameter("currentCount"));
        }
        StudentDao studentDao = new StudentDao();

        //调用业务层分页查询所有的装备信息
        PageBean<Student> pageBean = null;
        String msg = "查询成功";
        try {
            pageBean = studentDao.getStudents(currentPage, currentCount);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            msg = "查询失败";
        }
        Map<String, Object> pageBeanMap = new HashMap<String, Object>();
        pageBeanMap.put("status", 200);
        pageBeanMap.put("hint", msg);
        pageBeanMap.put("total", pageBean.getTotalCount());
        pageBeanMap.put("rows", pageBean.getList());
        System.out.println("GetStudentServlet方法返回值========");
        System.out.println(pageBeanMap);
        System.out.println("GetStudentServlet方法返回值========");

        response.setCharacterEncoding("utf-8");
        response.setContentType("charset=utf-8;json/html");
        try {
            response.getWriter().write(MapperUtils.obj2json(pageBeanMap));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
